<template>
  <div class="BasicInfo-container">
    <a-spin :spinning="loadingState.isLoad">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :rules="rules"
      >
        <title-name title="组织信息" />
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="用户名称"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="name"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入用户名称"
                v-model="formInfo.name"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="用户账号"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="username"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入用户账号(手机号码)"
                v-model="formInfo.username"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="身份证号"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="idCard"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入身份证号"
                v-model="formInfo.idCard"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="账号类型"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              :prop="pageType === 'add' ? 'accountType' : void 0"
            >
              <!-- 目前不允许修改账号类型，因此只能在新增时可选 -->
              <a-select
                :disabled="pageType !== 'add' || $route.meta.isPim"
                v-model="formInfo.accountType"
                placeholder="请选择账号类型"
              >
                <a-select-option
                  v-for="item in accountTypeList"
                  :key="item.id"
                  :value="item.id"
                >{{
                item.name
              }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="手机号码"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="phone"
            >
              <BaseInput
                disabled
                placeholder="请输入手机号码"
                v-model="formInfo.phone"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <title-name title="员工信息" />
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="性别"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="sex"
            >
              <a-select
                :disabled="isLook"
                v-model="formInfo.sex"
                placeholder="请选择性别"
              >
                <a-select-option
                  v-for="item in genderList"
                  :key="item.id"
                  :value="item.id"
                >{{
                item.name
              }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="年龄"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="age"
            >
              <BaseInputNumber
                :isInt="true"
                :disabled="isLook"
                placeholder="请输入年龄"
                v-model="formInfo.age"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="出生日期"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="birthday"
            >
              <a-date-picker
                :disabled="isLook"
                v-model="formInfo.birthday"
                value-format="YYYY-MM-DD"
                :placeholder="isLook ? '' : '请选择出生日期'"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="专业"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="specialitie"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入专业"
                v-model="formInfo.specialitie"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="职称"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="jobTitle"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入职称"
                v-model="formInfo.jobTitle"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="员工编号"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="jobNum"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入员工编号"
                v-model="formInfo.jobNum"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="最高学历专业"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="specialitieMax"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入最高学历专业"
                v-model="formInfo.specialitieMax"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="第一学历"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="firstEducation"
            >
              <a-select
                :disabled="isLook"
                v-model="formInfo.firstEducation"
                placeholder="请选择第一学历"
              >
                <a-select-option
                  v-for="item in educationList"
                  :key="item.id"
                  :value="item.name"
                >{{
                item.name
              }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="第二学历"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="secondEducation"
            >
              <a-select
                :disabled="isLook"
                v-model="formInfo.secondEducation"
                placeholder="请选择第二学历"
              >
                <a-select-option
                  v-for="item in educationList"
                  :key="item.id"
                  :value="item.name"
                >{{
                item.name
              }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="在职状态"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="status"
            >
              <a-select
                :disabled="isLook"
                v-model="formInfo.status"
                placeholder="请选择在职状态"
              >
                <a-select-option
                  v-for="item in jobStatusList"
                  :key="item.id"
                  :value="item.id"
                >{{
                item.name
              }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="邮箱"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="email"
            >
              <BaseInput
                :disabled="isLook"
                placeholder="请输入邮箱"
                v-model="formInfo.email"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <!-- 编辑时，弹出的二次授权弹窗 -->
    <a-modal
      v-model="visibleState.reAuth"
      title="二次授权"
      :confirmLoading="loadingState.reAuth"
      @ok="handleReAuth()"
      @cancel="handleCancelReAuth"
    >
      <a-form-model
        ref="ruleFormPsw"
        :model="formPsw"
        :rules="rulesPsw"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
        style="padding-right: 40px"
      >
        <a-form-model-item
          label="请输入密码"
          prop="psw"
        >
          <BaseInput
            v-model="formPsw.psw"
            type="password"
            placeholder="请输入密码"
          ></BaseInput>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { addUserManageList, editUserManageList } from '@/api/system/system'
import { getUsersDetail } from '@/api/commons.js'
import { accountTypeList, genderList, educationList, jobStatusList } from './model'
import { isIntNumber, createValidator, idCard, isEmail } from '@/utils/regExpression.js'

export default {
  name: 'BasicInfo',
  props: {
    employeeId: {
      type: String,
      default: ''
    },
    userId: {
      type: String,
      default: ''
    },
    pageType: {
      type: String,
      default: 'add'
    },
    commonData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loadingState: {
        reAuth: false,
        isLoad: false
      },
      visibleState: {
        reAuth: false
      },
      jobStatusList,
      educationList,
      genderList,
      accountTypeList,
      formInfo: {
        phone: ''
      },
      rules: {
        name: [{ required: true, message: '请输入用户名称', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { validator: createValidator(isIntNumber, '请输入正确的手机号码', false, this.afterUsernameDone), trigger: 'blur' }
        ],
        accountType: [{ required: true, message: '请选择账号类型', trigger: 'change' }],
        status: [{ required: true, message: '请选择在职状态', trigger: 'change' }],
        idCard: [{ validator: createValidator(idCard, '请输入正确的身份证号码'), trigger: 'blur' }],
        email: [{ validator: createValidator(isEmail, '请输入正确的邮箱'), trigger: 'blur' }]
      },
      formPsw: {
        psw: ''
      },
      submitParams: {},
      rulesPsw: {
        psw: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      callbackArgs: []
    }
  },
  computed: {
    // 查看和个人信息管理时禁止编辑
    isLook() {
      return this.pageType === 'look' || this.$route.meta.isPim
    }
  },
  created() {
    this.getEmployeeDetail()
  },
  methods: {
    /**
     * 在填写用户账号后，将手机号表单项同步
     */
    afterUsernameDone({ valid }) {
      if (valid) {
        this.formInfo.phone = this.formInfo.username
      } else {
        this.formInfo.phone = ''
      }
    },
    handleCancelReAuth() {
      const [resolve, reject] = this.callbackArgs
      reject && reject()
      this.visibleState.reAuth = false
    },
    /**
     * 二次授权
     * @param {Boolean} flag 是否需要二次授权，当为false时，不传二次授权密码
     */
    handleReAuth(flag = true) {
      const [resolve, reject] = this.callbackArgs
      const execFn = async () => {
        if (this.loadingState.reAuth) return
        this.loadingState.reAuth = true
        this.submitParams.employee.id = this.employeeId
        this.submitParams.employee.type = 0 // 用户标签
        if (flag) {
          this.submitParams.baseInfo.pscode = this.formPsw.psw
        }
        this.submitParams.baseInfo.orgId = this.selectedKeys
        try {
          const res = await editUserManageList(this.submitParams)
          this.$emit('update:commonData', res.data)
          this.$message.success('提交成功')
          resolve && resolve()
        } catch (e) {
          reject && reject()
          console.error(e)
        } finally {
          this.handleCancelReAuth()
          this.loadingState.reAuth = false
        }
      }
      if (flag) {
        this.$refs.ruleFormPsw.validate((valid) => {
          if (!valid) {
            return
          }
          execFn()
        })
      } else {
        execFn()
      }
    },
    async handleAddUser(params) {
      if (this.loadingState.reAuth) return
      this.loadingState.reAuth = true
      const [resolve, reject] = this.callbackArgs
      try {
        // 新增用户时，需要打上标签
        params.employee.type = 0
        const res = await addUserManageList({ ...params, tagCode: 'EM' })
        this.$emit('update:commonData', res.data)
        this.$message.success('提交成功')
        resolve && resolve()
      } catch (e) {
        console.error(e)
      } finally {
        this.handleCancelReAuth()
        this.loadingState.reAuth = false
      }
    },
    handleSubmit(...args) {
      const [resolve, reject, options] = args
      this.callbackArgs = args // 存储promise的回调函数，在编辑时，二次授权确认成功之后需要调用
      const { userId, specialitieMax, specialitie, status, secondEducation, firstEducation, sex, age, birthday, email, jobTitle, jobNum, name, username, accountType, phone, idCard } = this.formInfo
      const params = {
        employee: {
          specialitieMax,
          specialitie,
          status: status,
          secondEducation,
          firstEducation,
          sex,
          age,
          birthday,
          email,
          jobTitle,
          jobNum
        },
        baseInfo: {
          name,
          username,
          accountType,
          phone,
          idCard
        }
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message.warning("请填写完所有必填项信息")
          reject && reject()
          return
        }
        const fn = !this.employeeId
          ? this.handleAddUser
          : () => {
              if (options && options.isTab) {
                resolve && resolve()
                return
              }
              params.userId = userId
              this.submitParams = params
              // 如果是新增页面的二次提交，需要提示用户该操作为编辑
              if (this.pageType === 'add') {
                this.$message.warning('信息已存在，该操作将修改原数据')
              }
              // this.visibleState.reAuth = true
              this.handleReAuth(false)
            }
        fn(params)
      })
    },
    async getEmployeeDetail() {
      if (!this.userId) return
      try {
        if (this.loadingState.isLoad) return
        this.loadingState.isLoad = true
        const res = await getUsersDetail({
          userId: this.userId
        })
        this.formInfo = res.data || {}
        this.$emit('update:commonData', this.formInfo)
      } catch (e) {
        console.error(e)
      } finally {
        this.loadingState.isLoad = false
      }
    }
  }
}
</script>

<style>
</style>
